<template>
  <div>

    <el-upload ref="upload" :action="defaultSetting.uploadUrl" :headers="{AUTHORIZATION:token}" :data="{path:path}" :show-file-list="list" :file-list="files" :multiple="list" :on-success="handleSuccess" :on-remove="handleRemove" :limit="limit" :list-type="listType" :on-preview="hanldePreview">
      <slot/>
      <div slot="tip" class="tip-box">
        <el-button v-if="showClear" class="delete-btn" size="small" type="danger" @click="clear">清空</el-button>
        <el-button v-if="showClear" class="delete-btn" size="small" type="success" @click="priview">预览</el-button>

      </div>

    <!-- <slot name="tip" #tip /> -->
    </el-upload>
    <el-dialog :visible.sync="priviewDialog" append-to-body width="340px">
      <div class="priview-box">
        <img v-for="(item,index) in value" :key="index" :src="item" alt="">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import defaultSetting from '@/settings'
export default {
  name: 'MyUpload',
  props: {
    path: {
      type: String,
      default: ''
    },
    list: {
      type: Boolean,
      default: true
    },
    value: {
      type: [String, Array],
      default() {
        return []
      }
    },
    limit: {
      type: Number,
      default: 99
    },
    'listType': {
      type: String,
      default: 'text'
    },
    show: {
      default: false,
      type: Boolean
    },
    showClear: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      defaultSetting,
      files: [],
      temps: [],
      canSortByName: true,
      priviewDialog: false
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  watch: {
    show(value) {
      if (value) {
        this.init()
      } else {
        this.$refs.upload.clearFiles()
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      if (this.list && this.value) {
        let value = []
        if (this.limit === 1) {
          value.push(this.value)
        } else {
          value = this.value
        }
        this.files = value.map(item => {
          let name = item.split('/')
          name = name[name.length - 1]
          return {
            name,
            url: item
          }
        })
      }
      this.canSortByName = this.value.length === 0
    },
    handleSuccess(res, file, fileList) {
      if (this.list && this.limit !== 1) {
        // const files = fileList.map(item => item.response.data[0].cos_url)
        let files = this.value
        if (this.canSortByName) {
          fileList.sort((a, b) => {
            const aName = a.name.split('.')[0]
            const bName = b.name.split('.')[0]
            console.log(aName, bName)
            return Number(aName) - Number(bName)
          })
          files = fileList.filter(item => item.status === 'success' && item.response.data.cos_url)
            .map(item => item.response.data.cos_url)
        } else {
          files.push(res.data.cos_url)
        }
        console.log(fileList.map(item => item.name), files)
        this.$emit('input', files)
      } else {
        this.$emit('input', res.data.cos_url)
      }
    },
    clear() {
      this.$refs.upload.clearFiles()
      this.canSortByName = true
      this.$emit('input', this.limit === 1 ? '' : [])
    },
    handleRemove(file, fileList) {
      if (this.limit === 1) {
        return this.$emit('input', '')
      }
      const files = this.value
      const index = files.indexOf(file.url)
      files.splice(index, 1)
      if (files.length === 0) {
        this.canSortByName = true
      }
      this.$emit('input', files)
    },
    hanldePreview(file) {
      window.open(file.url)
      // clip(file.url, '复制地址成功')
    },
    priview() {
      this.priviewDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.tip-box{
  display: inline-block;
}
.delete-btn{
  margin-left: 10px;
}
.priview-box{
  width: 300px;
  img{
    display: block;
    width: 100%;
  }
}
</style>
